<template>
  <div class="ui-prop">
    <div class="label" :style="{'text-align':align}" @contextmenu="onContextMenu">
      {{ label }}
    </div>
    <div class="value">
      <template v-if="$slots.default">
        <slot></slot>
      </template>
      <template v-else>
        <SInput @change="onChangeData" v-if="isStringData"
                v-model:value="propData"></SInput>
        <SCheckbox @change="onChangeData" v-if="isBoolData"
                   v-model:value="propData"></SCheckbox>
        <SInput @change="onChangeData" v-if="isNumber"
                v-model:value="propData"></SInput>
      </template>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, toRaw, watch } from 'vue';
import SInput from '@/ui-kit/input/input.vue';
import SCheckbox from '@/ui-kit/checkbox/checkbox.vue';

export default defineComponent({
  name: 's-prop',
  emits: ['update:data', 'menu'],
  components: { SCheckbox, SInput },
  props: {
    label: {
      type: String,
      default: '属性',
    },
    align: {
      type: String,
      default: 'left',
    },
    data: {
      type: [String, Number, Boolean],
    },
    ext: {},
  },
  setup(props, { emit }) {
    const isStringData = ref(typeof props.data === 'string');
    const isBoolData = ref(typeof props.data === 'boolean');
    const isNumber = ref(typeof props.data === 'number');
    const propData = ref(props.data);

    watch(() => props.data, (val) => {
      propData.value = val;
    });

    return {
      onChangeData() {
        emit('update:data', propData.value, toRaw(props.ext));
      },
      propData,
      isBoolData,
      isStringData,
      isNumber,
      onContextMenu(event: MouseEvent) {
        emit('menu', event);
      },
    };
  },
});
</script>

<style scoped lang="scss">
.ui-prop {
  display: flex;
  flex-direction: row;

  .label {
    box-sizing: border-box;
    padding-left: 4px;
    flex: 1;
    font-size: 14px;
    user-select: none;
    border: 1px solid #d5d9de;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  .value {
    text-align: left;
    border: 1px solid #d5d9de;
    flex: 2;
  }
}
</style>
